# 19/100 矩阵-螺旋矩阵
# leetcode第54题: https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-100-liked
# Date: 2024/11/29
from leetcode import test


def spiralOrder_cursor(matrix: list[list[int]]) -> list[int]:
    """模拟一个上下左右移动的光标
    注意: python中的 match-case 不同于java中的 switch-case, match-case 等价于 if elif else, 不能向下穿透.
    a = 0
    match a:
        case 0:
            a += 1
        case 1:
            a += 1
        case 2:
            print(a)
    这里代码将不会打印, 因为在case判断为0之后, 这段代码块就执行完毕了
    """
    m, n = len(matrix), len(matrix[0])
    if m == 1:
        return matrix[0]

    visited = [[False] * n for _ in range(m)]
    x, y = 0, 0  # 坐标, x表示行号, y表示列号
    direction = 0  # 坐标移动的方向, 0表示右, 1表示下, 2 表示左, 3表示上
    res = []
    while not visited[x][y]:
        res.append(matrix[x][y])
        visited[x][y] = True
        if direction == 0:
            if y + 1 == n or visited[x][y + 1]:
                direction = 1
            else:
                y += 1
        if direction == 1:
            if x + 1 == m or visited[x + 1][y]:
                direction = 2
            else:
                x += 1
        if direction == 2:
            if y - 1 < 0 or visited[x][y - 1]:
                direction = 3
            else:
                y -= 1
        if direction == 3:
            if x - 1 < 0 or visited[x - 1][y]:
                direction = 0
            else:
                x -= 1
            if direction == 0:
                if y + 1 == n or visited[x][y + 1]:
                    direction = 1
                else:
                    y += 1
    return res


if __name__ == '__main__':
    inp = [{"matrix": [[1, 2, 3], [4, 5, 6], [7, 8, 9]]}, {"matrix": [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]}, ]
    out = [[1, 2, 3, 6, 9, 8, 7, 4, 5], [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]]
    test.test_function(spiralOrder_cursor, inp, out)
    # test.test_function(spiralOrder_dfs, inp, out)
